using System;
using System.Collections.Generic;

namespace OpenLS.Spreadsheet.Collections
{
    using TKey = Int32;
    class CachedDictionary<TValue>
    {
        public IEnumerable<TKey> Keys { get { return _inner.Keys; } }

        public IEnumerable<TValue> Values
        {
            get { return _inner.Values; }
        }

        readonly Dictionary<TKey, TValue> _inner = new Dictionary<TKey, TValue>();
        private bool hasCache;
        private int lastKey;
        private TValue lastValue;

        public bool TryGetValue(TKey key, out TValue value)
        {
            if (hasCache && lastKey == key)
            {
                value = lastValue;
                return true;
            }
            bool result = _inner.TryGetValue(key, out value);
            if (result)
            {
                hasCache = true;
                lastKey = key;
                lastValue = value;
            }
            else
            {
                hasCache = false;
            }
            return result;
        }

        public void Add(TKey key, TValue value)
        {
            hasCache = false;
            _inner.Add(key, value);
        }

        public TValue this[TKey key]
        {
            get { return _inner[key]; }
        }
    }
}